// 双击折叠功能 - 支持标题和列表，桌面端与移动端
(() => {
    // 移动端双击检测
    let lastTap = 0;
    let tapTimer = null;
    
    // 存储事件处理函数引用，用于清理
    let dblclickHandler = null;
    let touchstartHandler = null;

    // 统一的事件处理函数
    function handleDoubleClick(event) {
        // 优先检查是否直接点击了标题
        const headingElement = event.target.closest('[data-type="NodeHeading"]');
        if (headingElement && headingElement.contains(event.target) && 
            !event.target.closest('.protyle-gutters')) {
            
            event.preventDefault();
            const nodeId = headingElement.dataset?.nodeId;
            if (nodeId) {
                foldBlock(nodeId, !headingElement.getAttribute('fold'));
                return;
            }
        }
        
        // 检查是否是列表项
        const listItemElement = event.target.closest('[data-type="NodeListItem"]');
        if (listItemElement && listItemElement.contains(event.target) && 
            !event.target.closest('.protyle-gutters')) {
            
            const nodeId = listItemElement.dataset?.nodeId;
            if (!nodeId) return;
            
            const isCurrentlyFolded = listItemElement.getAttribute('fold');
            
            // 如果当前是折叠状态，允许展开
            if (isCurrentlyFolded) {
                event.preventDefault();
                foldBlock(nodeId, false); // 展开
                return;
            }
            
            // 如果当前是展开状态，检查是否有嵌套的列表结构
            const nestedList = listItemElement.querySelector('[data-type="NodeList"]');
            if (!nestedList) {
                // 没有嵌套列表，不进行折叠操作
                return;
            }
            
            event.preventDefault();
            foldBlock(nodeId, true); // 折叠
            return;
        }
        
        // 检查是否是列表容器
        const listElement = event.target.closest('[data-type="NodeList"]');
        if (listElement && listElement.contains(event.target) && 
            !event.target.closest('.protyle-gutters')) {
            
            event.preventDefault();
            const nodeId = listElement.dataset?.nodeId;
            if (nodeId) {
                foldBlock(nodeId, !listElement.getAttribute('fold'));
            }
        }
    }

    // 移动端触控处理函数
    function handleTouchStart(event) {
        const now = Date.now();
        const timeDiff = now - lastTap;
        
        if (timeDiff < 300 && timeDiff > 0) {
            clearTimeout(tapTimer);
            handleDoubleClick(event);
        }
        
        lastTap = now;
        tapTimer = setTimeout(() => {}, 300);
    }

    // 根据是否有侧边栏判断设备类型
    if (document.getElementById("sidebar")) {
        // 移动端：触控连续敲击
        touchstartHandler = handleTouchStart;
        document.addEventListener('touchstart', touchstartHandler);
    } else {
        // 桌面端：鼠标双击
        dblclickHandler = handleDoubleClick;
        document.addEventListener('dblclick', dblclickHandler);
    }

    async function foldBlock(id, isFold) {
        await fetch('/api/block/' + (isFold ? 'foldBlock' : 'unfoldBlock'), {
            method: "POST",
            body: JSON.stringify({id: id})
        });
    }

    /**
     * 注册清理函数，卸载时自动清理所有监听器
     */
    function registerCleanup() {
        const cleanup = () => {
            // 清理事件监听器
            if (dblclickHandler) {
                document.removeEventListener('dblclick', dblclickHandler);
                dblclickHandler = null;
            }
            if (touchstartHandler) {
                document.removeEventListener('touchstart', touchstartHandler);
                touchstartHandler = null;
            }
            
            // 清理定时器
            if (tapTimer) {
                clearTimeout(tapTimer);
                tapTimer = null;
            }
            
            // 重置变量
            lastTap = 0;
        };
        
        const currentScript = document.currentScript?.src;
        if (!currentScript) {
            console.log('无法确定当前脚本路径，loadSnippets后续清理函数未注册。');
            return;
        }
        const currentFilename = currentScript.split('/').pop();
        if (window.__registerCleanupHandler) {
            window.__registerCleanupHandler(currentFilename, cleanup);
        } else {
            console.log('未接入代码片段loadSnippets，清理注册接口不可用');
        }
    }
    registerCleanup();
})(); 